﻿using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Lari.Configuration;
using Lari.Framework.Utility;

namespace Lari.Web.Utility
{
    public class AccessFilterAttribute : ActionFilterAttribute
    {
        private readonly int _accessId;
        private readonly string _view;

        public AccessFilterAttribute(int accessId,bool isPopup=false)
        {
            _accessId = accessId;
            _view = isPopup ? "NoAccessPopup" : "NoAccess";
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext == null || filterContext.HttpContext == null || filterContext.HttpContext.User == null)
                return;

            var cookie = filterContext.HttpContext.Request.Cookies[CookieName.AccessCsv];
            if (cookie != null)
            {
                var accessCsv = Encryption.Decrypt(cookie.Value);
                if (string.IsNullOrEmpty(accessCsv))
                {
                    var result = new ViewResult { ViewName = _view };
                    result.ViewBag.AccessId = _accessId;
                    filterContext.Result = result;
                }
                else
                {
                    var list = accessCsv.Split(',');
                    if (!list.Any(s => s == _accessId.ToString(CultureInfo.InvariantCulture)))
                    {
                        var result = new ViewResult { ViewName = _view };
                        result.ViewBag.AccessId = _accessId;
                        filterContext.Result = result;
                    }
                }
            }
            else
            {
                var result = new ViewResult { ViewName = _view };
                result.ViewBag.AccessId = 0;
                filterContext.Result = result;
            }
        }
    }
}